/**
 * @description: 文件描述
 * @version: 0.0.1
 * @author: ljr
 * @Date: 2023-09-12 15:47:16
 */
import { Provide, Inject, httpError } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
const moment = require('moment');
const uuid = require("uuid");
const xlsx = require('node-xlsx');
const fs = require('fs');
import { FileUtils } from '../utils/file'
import { OrdersRecordsModel } from '../entity/orders_records.methods'
import { ProjectRecordModel } from '../entity/project_records.methods';
import { ProjectOrderContactModel } from '../entity/project_order_contact.methods';
import { OrdersCostRecordsModel } from '../entity/orders_cost.methods';

@Provide()
export class OrdersService {
  @Inject()
  ctx: Context;
  @Inject()
  OrdersRecordsModel: OrdersRecordsModel;
  @Inject()
  ProjectRecordModel: ProjectRecordModel;
  @Inject()
  ProjectOrderContactModel: ProjectOrderContactModel;
  @Inject()
  OrdersCostRecordsModel: OrdersCostRecordsModel;

  @Inject()
  FileUtils: FileUtils
  /**
   * 创建订单
   * @param {*} accessToken 
   * @returns 
   */
  async createdOrder(params: any): Promise<any> {
    const { ctx } = this;
    const userInfo = ctx.userInfo;
    const { orderName, orderDetails, createdProject, remarks, orderId, brandName } = params;

    const belongDate = moment().format('YYYY-MM-DD');
    // 创建订单信息
    const insertRes = await this.OrdersRecordsModel.insertOrders({
      orderName: orderName,
      orderDetails: orderDetails || "",
      orderId: orderId || "",
      remarks: remarks || "",
      belongDate: belongDate,
      createdUserid: userInfo.id,
      createdUsername: userInfo.nick,
      brandName: brandName || ""
    });
    if (!insertRes) throw new httpError.BadRequestError("订单信息存储失败")
    //  需要自动创建项目
    if (Number(createdProject)) {
      //  创建项目信息
      const insertProj = await this.ProjectRecordModel.insertProjectInfo({
        projectName: `${orderName}-项目`,
        projectContent: "",
        projectProgress: "",
        projectType: "",
        userId: "",
        userName: "",
        createUserid: userInfo.id,
        createUsername: userInfo.nick,
        brandName: brandName || ""
      });

      //  新增项目订单关联关系
      await this.ProjectOrderContactModel.insertContact({
        projId: insertProj,
        orderId: insertRes
      })
      return "订单-项目创建成功";
    } else {
      return "订单创建成功";
    }
  }

  /**
   * 创建订单编号
   */
  async createdOrderId(): Promise<any> {
    const orderLen = 4;
    const belongDate = moment().format('YYYY-MM-DD');
    const count = await this.OrdersRecordsModel.getCountByDate(belongDate);
    const num = count[0].total + 1;

    const _orderNum = (Array(orderLen).join('0') + num).slice(-orderLen);
    // 创建订单编号
    const _orderId = `${moment().format('YYYYMMDD')}${_orderNum}`;
    return {
      orderId: _orderId,
      belongDate: belongDate
    }
  }

  /**
   * 订单信息分页查询
   * @param {*} params 
   */
  async getOrderPage(params: any): Promise<any> {
    const { pageSize, pageNum, searchKey } = params;
    const total = await this.OrdersRecordsModel.getTotalNum(searchKey);
    const res = {
      total: total[0].num,
      lists: []
    }

    if (total[0].num) {
      const resList = await this.OrdersRecordsModel.getDataByPage(pageNum, pageSize, searchKey);
      res.lists = resList;
    }
    return res
  }

  /**
   * 删除订单数据
   * @param {*} id
   */
  async delOrderInfo(params: any): Promise<any> {
    //  查询订单数据
    const orderInfo = await this.OrdersRecordsModel.getDataById(params.id);
    if (!orderInfo || !orderInfo[0] || !orderInfo[0].id) throw new httpError.BadRequestError("订单信息不存在")
    //  查询当前订单是否关联项目信息
    const projCount = await this.ProjectOrderContactModel.getCountByOrderId(orderInfo[0].id);

    if (projCount[0].total) throw new httpError.BadRequestError("订单数据已被关联项目，不能删除")

    await this.OrdersRecordsModel.delDataById(params.id);
    return '删除成功'
  }

  /**
   * 修改订单信息
   * @param {*} params 
   */
  async updateOrderInfo(params: any): Promise<any> {
    await this.OrdersRecordsModel.updateDataById({
      id: params.id,
      orderName: params.orderName,
      orderDetails: params.orderDetails,
      remarks: params.remarks || "",
      orderId: params.orderId || "",
      brandName: params.brandName || ""
    });
    return "修改成功"
  }

  /**
   * 订单数据导入
   */
  async uploadOrdersFile(): Promise<any> {
      const { ctx } = this;
      const userInfo = ctx.userInfo;
      // 获取文件
      const stream = ctx.files[0];
      // 文件流写本地文件
      const localPath = await this.FileUtils.fileStreamUpload(stream, uuid.v4());
      const excelData = xlsx.parse(localPath);
      let newArr = excelData[0]['data'];
      newArr.shift();
      // 过滤掉excel中空的行
      newArr = newArr.filter((item) => item.length);

      const successRes = [];
      const errorRes = [];
      for (let i = 0; i < newArr.length; i++) {
        const item = newArr[i];
        // 获取订单编码
        const belongDate = moment().format('YYYY-MM-DD');

        if (item[0]) {
          // 创建订单信息
          const insertRes = await this.OrdersRecordsModel.insertOrders({
            orderName: item[0],
            orderDetails: item[1] || "",
            orderId: item[2] || "",
            remarks: item[3] ? String(item[3]).trim() : "",
            belongDate: belongDate,
            createdUserid: userInfo.id,
            createdUsername: userInfo.nick,
            brandName: ""
          });
          successRes.push(insertRes);
        } else {
          errorRes.push({ orderName: item[0], orderDetails: item[1], orderId: item[2], remarks: item[3] });
        }
      }

      //上传完成  删除临时文件
      fs.unlinkSync(localPath);
      return { successRes, errorRes };
  }

  /**
   * 获取订单详情
   * @param params 
   */
  async getOrdersDetailsById(params: any): Promise<any> {
    //  查询订单详情
    const orderInfo = await this.OrdersRecordsModel.getDataById(params.id);
    // 查询订单管理的项目信息
    const workingLists = await this.ProjectOrderContactModel.getOrderDataByOrderId(params.id);
    return {
      orderDetails: orderInfo[0] || {},
      workingLists
    };
  }

  /**
   * 获取订单其他成本数据
   * @param orderId 
   * @returns 
   */
  async getOrderCostLists(orderId: number): Promise<any> {
    return await this.OrdersCostRecordsModel.getDataByOrderId(orderId);
  }

  /**
   * 新增订单其他成本数据
   * @param params 
   * @returns 
   */
  async createOrderCostInfo(params: { cost_name: string, cost_amount: number, cost_remark: any, order_id: number }): Promise<any> {
    return await this.OrdersCostRecordsModel.insertData({
      cost_name: params.cost_name,
      cost_amount: params.cost_amount,
      cost_remark: params.cost_remark || "",
      order_id: params.order_id
    });
  }

  /**
   * 更新订单其他成本数据
   * @param params 
   * @returns 
   */
  async updateOrderCostInfo(params: { cost_name: string, cost_amount: number, cost_remark: any, id: number}): Promise<any> {
    return await this.OrdersCostRecordsModel.updateDataById({
      id: params.id,
      cost_name: params.cost_name,
      cost_amount: params.cost_amount,
      cost_remark: params.cost_remark || ""
    });
  }

  /**
   * 删除订单其他成本数据
   * @param params 
   * @returns 
   */
  async delOrderCostInfo(id: number): Promise<any> {
    return await this.OrdersCostRecordsModel.delDataById(id);
  }
}